package com.chance.cc.crawler.development.scripts.du.phone;

import com.chance.cc.crawler.sheduler.job.context.ScheduleHandlerContext;
import com.chance.cc.crawler.sheduler.job.handler.SchedulerHandler;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.vidstige.jadb.JadbDevice;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static com.chance.cc.crawler.sheduler.job.handler.phone.AdbShellUtils.*;

/**
 * @author bx
 * @date 2020/12/4 0004 11:28
 */
public class DUPHotNewstMI5SADBScript extends SchedulerHandler{

    private static Logger log = LoggerFactory.getLogger(DUPHotNewstMI5SADBScript.class);

    @Override
    public String domain() {
        return "du_app";
    }

    @Override
    public boolean isHandle(ScheduleHandlerContext context) {
        return true;
    }

    @Override
    public void handle(ScheduleHandlerContext context) {

        //do some thing
        JadbDevice jadbDevice = context.getJadbDevice();
        Map<String, String> scheduleDataMap = context.getScheduleDataMap();
        int swipeNumbers = Integer.valueOf(scheduleDataMap.getOrDefault("phone_max_swipe_numbers", "100"));
        long startTime = Long.valueOf(scheduleDataMap.getOrDefault("crawler_list_start_time","0"));
        int hours = Integer.valueOf(scheduleDataMap.getOrDefault("crawler_list_hours","0"));

        if (hours > 0){
            startTime = System.currentTimeMillis() - hours*60*60*1000L;
        }
        try {
            duHotNewsList(jadbDevice,swipeNumbers,startTime,context);
        } catch (Exception e) {
            try {
                duHotNewsList(jadbDevice,swipeNumbers,startTime,context);
            } catch (Exception e1) {
                log.error(e.getMessage(),e1);
            }
        }
    }

    public void duHotNewsList(JadbDevice device,int swipeNumbers,long startTime,ScheduleHandlerContext context)  throws Exception {
        log.info("device {} du hot news list script--begin------------------",device.getSerial());

        //当前是否是在初始页面
        if(!initHome(device)){ //是否在通讯录页面
            throw new Exception("device "+device.getSerial()+" 无法初始到服务页面！");
        }

        //采集关键词
        String[] newsCoordinate = getCoordinate(dumpUI(device,3),"text","最新");
        if (newsCoordinate == null || newsCoordinate.length != 2){
            throw new Exception("device "+device.getSerial()+" Failed to get the hottest information list!");
        }

        //滑动屏幕，采集资讯
        for(int start=1;start<=swipeNumbers;start++){
            executeShell(device,"input swipe 540 1900 540 0 400");
            if (startTime > 0){ //传入时间则按照时间采集。否则按照最大翻页数采集
                if(start % 10 == 0){ // 每10次查看一次
                    List<String> releaseTimes = getTextNodeVaules(dumpUI(device, 3), "resource-id", "com.shizhuang.duapp:id/tv_last_time");
                    String lastTime = releaseTimes.get(releaseTimes.size() - 1);
                    long lastReleaseTime = dateToTimestamp(lastTime);
                    if (startTime > lastReleaseTime ){
                        log.info("device {} du hot news list turn page numbers {}",device.getSerial(),start);
                        break;
                    }
                }
            }
        }

        //返回到得物服务首页
        executeShell(device,"input keyevent 4");
        log.info("device {} du hot news list back service home",device.getSerial());
    }

    private boolean initHome(JadbDevice device) throws Exception {

        for(int backCOunt=0;backCOunt < 10;backCOunt++){
            ByteArrayOutputStream baos = dumpUIForOutPutStream(device,5);
            InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
            String[] homeCoordinate = getCoordinate(inputStream, "text", "服务", false);

            if (homeCoordinate != null && homeCoordinate.length == 2){
                inputStream = new ByteArrayInputStream(baos.toByteArray());
                String[] hotNewsCoordinate = getCoordinate(inputStream,"text","最新资讯");
                if (hotNewsCoordinate == null){
                    executeShell(3000,device,"input tap "+homeCoordinate[0]+" "+homeCoordinate[1]);
                } else {
                    executeShell(5000,device,"input tap "+hotNewsCoordinate[0]+" "+hotNewsCoordinate[1]);
                    return true;
                }
                continue;
            }
//            if (isUpdate(device,baos)){
//                continue;
//            }
//            if (isMailList(device,baos)){
//                continue;
//            }
//            if (isRemind(device,baos)){
//                continue;
//            }
            executeShell(3000,device,"input keyevent 4");
        }
        return false;
    }


    public long dateToTimestamp(String dataStr) throws ParseException {
        String regEx="[^0-9]+"; //正则表达式，用于匹配非数字串，+号用于匹配出多个非数字串
        Pattern pattern = Pattern.compile(regEx);

        if (dataStr.equals("刚刚")){
            return System.currentTimeMillis();
        } else if (Pattern.matches("\\d*秒前",dataStr)){
            int number = Integer.valueOf(pattern.split(dataStr)[0]);
            return (System.currentTimeMillis() - number*1000L);
        } else if (Pattern.matches("\\d*分钟前",dataStr)){
            int number = Integer.valueOf(pattern.split(dataStr)[0]);
            return (System.currentTimeMillis() - number*60*1000L);
        } else if (Pattern.matches("\\d*小时前",dataStr)){
            int number = Integer.valueOf(pattern.split(dataStr)[0]);
            return (System.currentTimeMillis() - number*60*60*1000L);
        } else if (Pattern.matches("\\d*小时\\d*分钟前",dataStr)){
            int hourNumber = Integer.valueOf(pattern.split(dataStr)[0]);
            int secondNumber = Integer.valueOf(pattern.split(dataStr)[1]);
            long totalMillis = hourNumber*60*60*1000L + secondNumber*60*1000L;
            return (System.currentTimeMillis() - totalMillis);
        } else if (Pattern.matches("\\d*天前",dataStr)){
            int number = Integer.valueOf(pattern.split(dataStr)[0]);
            return (System.currentTimeMillis() - number*24*60*60*1000L);
        } else if (dataStr.startsWith("今天")){
            String currentTime = DateFormatUtils.format(System.currentTimeMillis(), TimeForamtEnum.format1.getFormat());
            dataStr = dataStr.replace("今天", currentTime);
        } else if (dataStr.startsWith("昨天")){
            String yesterdayTime = DateFormatUtils.format(System.currentTimeMillis() - 60*60*24*1000L, TimeForamtEnum.format1.getFormat());
            dataStr = dataStr.replace("昨天", yesterdayTime);
        } else if (dataStr.startsWith("前天")){
            String beforeYesterdayTime = DateFormatUtils.format(System.currentTimeMillis() - 2*60*60*24*1000L, TimeForamtEnum.format1.getFormat());
            dataStr = dataStr.replace("前天", beforeYesterdayTime);
        } else if (Pattern.matches("\\d*月\\d*[日]*", dataStr)){
            Calendar cal = Calendar.getInstance();
            dataStr = cal.get(Calendar.YEAR)+"年"+dataStr;
        } else if (Pattern.matches("\\d*-\\d*", dataStr)){
            Calendar cal = Calendar.getInstance();
            dataStr = cal.get(Calendar.YEAR)+"-"+dataStr;
        }
        return DateUtils.parseDateStrictly(dataStr, TimeForamtEnum.allFormats()).getTime();
    }

    public enum TimeForamtEnum {
        format1("yyyy年MM月dd日"),
        format1_1("yyyy年MM月dd日 HH:mm:ss"),
        format1_2("yyyy年MM月dd日 HH:mm"),
        format1_3("yyyy年MM月dd日HH:mm"),
        format1_4("yyyy年MM月dd日 HH点mm分"),
        format1_5("yyyy年MM月dd日 HH点mm分ss秒"),
        format1_6("yyyy年MM月dd日HH点mm分"),
        format1_7("yyyy年MM月dd日HH点mm分ss秒"),


        format4("yyyy-MM-dd HH:mm:ss"),
        format5("yyyy-MM-dd HH:mm"),
        format6("yyyy-MM-dd"),

        format7("yyyy/MM/dd HH:mm:ss"),
        format7_1("MM/dd/yyyy HH:mm:ss"),
        format8("yyyy/MM/dd HH:mm"),
        format9("yyyy/MM/dd"),

        format10("yyyy.MM.dd HH:mm:ss"),
        format11("yyyy.MM.dd HH:mm"),
        format12("yyyy.MM.dd"),

        format13("EEE MMM d HH:mm:ss +0800 yyyy");

        private String format;

        private TimeForamtEnum(String format) {
            this.format = format;
        }

        public static String[] allFormats() {
            TimeForamtEnum[] timeForamtEnums = TimeForamtEnum.values();
            String[] formats = new String[timeForamtEnums.length];
            for (int count = 0; count < timeForamtEnums.length; count++) {
                formats[count] = timeForamtEnums[count].format;
            }
            return formats;
        }

        public String getFormat() {
            return format;
        }
    }
}
